<?php

class GaAPI_Services_Campaigns extends GaAPI_Services_Abstract {

    protected $_serviceName = 'CampaignService';

    protected function call($name, $params = false) {
        if ($this->getApi()->checkParam('client_email')) {
            return parent::call($name, $params);
        }
        return $this->throwError("Campaigns methods require clients_email to be set");
    }

    /**
     * @return GaAPI_Objects_Campaign_Page
     */
    public function getAll() {
        $selector = $this->newSelector();
        return $this->get($selector);
    }

    /**
     *
     * @param GaAPI_Objects_Campaign_Selector $selector
     * @return GaAPI_Objects Campaign_Page
     */
    public function get(GaAPI_Objects_Campaign_Selector $selector) {
        $result = $this->call('get',(string) $selector);
        $campaignPage = $this->newPage();
        $campaignPage->setApi($this->getApi());
        $campaignPage->setFromArray($result['rval']);

        return $campaignPage;
    }

    public function addNew(GaAPI_Objects_Campaign $campaign) {
        $request_xml = '<mutate xmlns="' . $this->getClient()->getNamespace() . '">';
        $request_xml .= '<operations>';
            $request_xml .= '<operator>ADD</operator>';
            $request_xml .= '<operand>' . $campaign . '</operand>';
        $request_xml .= '</operations>';
        $request_xml .= '</mutate>';

        $return = $this->call('mutate', $request_xml);
        return $this->newCampaign()->setFromArray($return['rval']['value']);
    }

    /**
     * @return GaAPI_Objects_Campaign
     */
    public function newCampaign() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_Campaign');
        $campaign = new GaAPI_Objects_Campaign();
        return $campaign;
    }


    /**
     * @return GaAPI_Objects_Campaign_Selector
     */
     public function newSelector() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_Campaign_Selector');
        $selector = new GaAPI_Objects_Campaign_Selector();
        $selector->setApi($this->getApi());
        return $selector;
    }

    /**
     * @return GaAPI_Objects_Campaign_Page
     */
     public function newPage() {
        GaAPI_Autoloader::instance()->load('GaAPI_Objects_Campaign_Page');
        $page = new GaAPI_Objects_Campaign_Page();
        return $page;
    }

}